<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="shop.js"></script>
    <script>
        function $(id){
            return document.getElementById(id);
        }
        window.onload = function (){
            showShopInfo();
        }

        /**
         * 显示购物车信息
         */
        function showShopInfo(){
            //购物车总价
            let total = 0;
            let str = "";
            shopArray.forEach(n => {
               str += `<tr><td>${n.pcode}</td><td>${n.pname}</td>
                <td>${n.price}</td><td><input type="number" min="1" value="${n.num}"
                    onblur="updateNum(${n.pcode},this)"></td>
                <td>${n.price * n.num}</td><td>
                <input type="button" value="移除商品" onclick="del(${n.pcode})"></td></tr>`;
                total += n.price * n.num;
            })
            $("data").innerHTML = str;
            $("totalSpan").innerHTML = "￥"+total;
        }

        /**
         * 修改购买数量
         * @param code 要修改购物车的编号
         * @param txtObj 数量文本框
         */
        function updateNum(code,txtObj){
            //找到指定编号对应的购物车对象
            var shopObj = shopArray.find(n => n.pcode == code);
            shopObj.num = txtObj.value;
            showShopInfo();
        }

        /**
         * 移除购物车商品
         * @param code 要移除的编号
         */
        function del(code){
            //找到指定编号商品对应的下标
            let index = shopArray.findIndex(n => n.pcode == code);
            shopArray.splice(index,1);
            showShopInfo();
        }
    </script>
</head>
<body>
    <table border="1" width="60%" cellspacing="0">
        <thead>
            <tr><th>商品编号</th><th>商品名</th><th>单价</th><th>购买数量</th>
                <th>单项总价</th><th>操作</th></tr>
        </thead>

        <tbody id="data"></tbody>
    </table>
    购物车总价：<span id="totalSpan"></span>
</body>
</html>